import { defineStore } from 'pinia'
import { useKey } from './keys'

interface IUserState {
    menus: IMenuModel[];
    username: string;
}
type menu = IMenuModel & { children: IMenuModel[] };
export const useUserStore = defineStore(useKey, {
    state(): IUserState {
        return {
            menus: [],
            username: ""
        }
    },
    getters: {
        routers() {
            let menus: menu[] = [];
            // 找到所有的1级
            menus = this.menus
                .filter((item) => item.parentId === 0)
                .map((item) => ({
                    ...item,
                    children: [],
                }));

            // 继续把2级加入对应的1级的children
            this.menus.forEach((sub) => {
                // 找到 menus 1级里面的id和我的parentId相等的，就我的上级
                const p = menus.find((item) => item.id === sub.parentId);
                // 如果找到了我的上级，加入它的children
                if (p) {
                    p.children.push(sub);
                }
            });

            return menus;
        },
        permissions(): string[] {
            return this.menus.map(item => item.name)
        }
    }
})